package com.estronger.shopmanage.utils;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.view.View;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.ui.MainActivity;
import com.estronger.shopmanage.view.messagedialog.AlertDialog;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.GET_ACCOUNTS;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.support.v4.content.PermissionChecker.PERMISSION_DENIED;
import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;

/**
 * Created by Administrator on 2017-05-19.
 */

public class PermissionUtils {

    private static PermissionUtils instance;

    private PermissionUtils() {
    }

    public static PermissionUtils getInstance() {    //对获取实例的方法进行同步
        if (instance == null) {
            synchronized (PermissionUtils.class) {
                if (instance == null)
                    instance = new PermissionUtils();
            }
        }
        return instance;
    }

    /*
     * 检查是否开启了定位权限
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 强制开启定位权限
     *
     * @param context
     * @return
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /*是否开启获取手机识别码的权限*/
    public static boolean isReadPhoneGranted(Context context) {
        if (ContextCompat.checkSelfPermission(context, READ_PHONE_STATE) == PERMISSION_GRANTED) {
            return true;
        } else if (ContextCompat.checkSelfPermission(context, READ_PHONE_STATE) == PERMISSION_DENIED) {
            return false;
        }
        return false;
    }

    /*是否有手机摄像头权限*/
    public static boolean isCameraGranted(Context context) {
        try {
            if (ContextCompat.checkSelfPermission(context, CAMERA) == PERMISSION_GRANTED) {
                boolean canUse = true;
                Camera mCamera = null;
                try {
                    mCamera = Camera.open();
                    // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
                    Camera.Parameters mParameters = mCamera.getParameters();
                    mCamera.setParameters(mParameters);
                } catch (Exception e) {
                    canUse = false;
                }
                if (mCamera != null) {
                    mCamera.release();
                }
                return canUse;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static void openToScan(final Activity activity, final OpenListener listener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.getInstance().requestPromisssions(activity, new AcceptListener() {
                @Override
                public void grante() {
                    listener.open();
                }

                @Override
                public void denial(Permission permission) {
                    android.widget.Toast.makeText(activity, "您关闭了摄像头权限，无法使用扫码", android.widget.Toast.LENGTH_SHORT).show();
                }

                @Override
                public void fail() {

                }
            },Manifest.permission.CAMERA);
        } else {
            if (isCameraGranted(activity)) listener.open();
            else ToSetPermissions(activity, R.string.PermissionsSCAN);
        }
    }

    /*是否有读取本地存储权限*/
    public static boolean isReadWriteGranted(final Context context) {
//        boolean flag = false;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            Intent cameraIntent = new Intent(Intent.ACTION_VIEW);
//            // 设置系统相机拍照后的输出路径
//            // 创建临时文
//            File mTmpFile = null;
//            try {
//                mTmpFile = me.nereo.multi_image_selector.utils.FileUtils.createTmpFile(context);
//            } catch (IOException e) {
//                flag = false;
//            }
//            try {
//                Uri photoOutputUri = FileProvider.getUriForFile(context, "com.estronger.shopmanage" + ".fileprovider", mTmpFile);
//                flag = true;
//            } catch (Exception e) {
//                e.fillInStackTrace();
//                flag = false;
//            }
//        }else{
//            flag = true;
//        }
        return ContextCompat.checkSelfPermission(context, READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED;
    }

    /*是否有访问麦克风的权限*/
    public static boolean isRecordAudioGranted(Context context) {
        return ContextCompat.checkSelfPermission(context, RECORD_AUDIO) == PERMISSION_GRANTED;
    }

    /*是否有访问通讯录的权限*/
    public static boolean isGetAccountsGranted(Context context) {
        return ContextCompat.checkSelfPermission(context, GET_ACCOUNTS) == PERMISSION_GRANTED;
    }

    /**
     * 是否有拨打电话的权限
     **/
    public static boolean isCallPhoneGranted(Context context) {
        return ContextCompat.checkSelfPermission(context, CALL_PHONE) == PERMISSION_GRANTED;
    }

    /*提示设置引导对话框*/
    public static void ToSetPermissions(final Context context, int stringId) {
        try {
            new AlertDialog(context).builder().setTitle("权限申请").setMsg(context.getResources().getString(stringId))
                    .setPositiveButton("去设置", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //getAppDetailSettingIntent(mContext);
                            Intent intent = new Intent("/");
                            ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.RunningServices");
                            intent.setComponent(cm);
                            intent.setAction("android.intent.action.VIEW");
                            context.startActivity(intent);
                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            }).show();
        } catch (Exception e) {
        }
    }

    /**
     * 判断是否是快速点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {

            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 使用第三方框架询问权限
     *
     * @param activity
     * @param accept
     * @param permissions
     */
    public void requestPromisssions(Activity activity, final AcceptListener accept, String... permissions) {
        new RxPermissions(activity).request(permissions).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean){
                try {
                    if (aBoolean) {
                        accept.grante();
                    } else {
                        accept.fail();
                    }
                }catch (Exception e){
                    accept.fail();
                }

            }
        });
    }

    public interface OpenListener {
        void open();
    }

    public interface AcceptListener {
        void grante();

        void denial(Permission permission);

        void fail();
    }
}
